package cnpm.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import cnpm.dao.ConditionSearchDAO;
import cnpm.entity.ConditionSearch;
import cnpm.entity.User;
import cnpm.util.HibernateUtil;

public class ConditionSearchDAOImpl implements ConditionSearchDAO {

	private SessionFactory sessionFactory;
	private Session session;
	
	public ConditionSearchDAOImpl() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}
	
	@Override
	public boolean saveOrUpdateConditionSearch(ConditionSearch cs) {
		try{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.saveOrUpdate(cs);
			session.beginTransaction().commit();
			return true;
		}catch(HibernateException e1){
			if(session.beginTransaction() == null){
				session.beginTransaction().rollback();
			}
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ConditionSearch> getAllConditionSearch(User user) {
		List<ConditionSearch> list = new ArrayList<ConditionSearch>();
		try{
			session = sessionFactory.openSession();
			list = (List<ConditionSearch>)session.createCriteria(ConditionSearch.class)
					.add(Restrictions.eq("user", user))
					.list();
		}catch(HibernateException e){
			e.printStackTrace();
		}
		finally{
			session.close();
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isExitsConditionSearch(String condition) {
		List<ConditionSearch> list = new ArrayList<ConditionSearch>();
		try{
			session = sessionFactory.openSession();
			list = (List<ConditionSearch>)session.createCriteria(ConditionSearch.class)
					.add(Restrictions.eq("condition", condition))
					.list();
		}catch(HibernateException e){
			e.printStackTrace();
		}
		finally{
			session.close();
		}
		return list.size() != 0?true:false;
	}

}
